import cv2
import matplotlib.pyplot as plt
import numpy as np
import os

# 读取图像
image = cv2.imread(r"C:\Users\86177\Desktop\hanzi1.jpg")

# 将图像转换为灰度图
gray = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 二值化处理
ret, binary = cv2.threshold(gray, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

# 查找轮廓
contours, hierarchy = cv2.findContours(binary, cv2.RETR_EXTERNAL, cv2.CHAIN_APPROX_SIMPLE)

# 遍历所有轮廓并绘制绿色框
for contour in contours:
    x, y, w, h = cv2.boundingRect(contour)
    if w > 10 and h > 10: # 过滤掉过小的轮廓
        cv2.rectangle(image, (x, y), (x+w, y+h), (0, 255, 0), 2)

# 显示图像
plt.imshow(cv2.cvtColor(image, cv2.COLOR_BGR2RGB))
plt.axis('off')
plt.show()

# 读取图像
image = plt.imread(r"C:\Users\86177\Desktop\hanzi1.jpg")

# 打印灰度图
plt.imshow(image, cmap='gray')
plt.title('Grayscale Image')
plt.show()

# 将图像转换为灰度格式
gray_image = cv2.cvtColor(image, cv2.COLOR_BGR2GRAY)

# 应用阈值处理
_, binary_image = cv2.threshold(gray_image, 0, 255, cv2.THRESH_BINARY_INV + cv2.THRESH_OTSU)

# 打印二值化图
plt.imshow(binary_image, cmap='gray')
plt.title('Binary Image')
plt.show()

# 应用腐蚀操作
kernel = np.ones((5, 5), np.uint8)  # 修改核大小为5x5
eroded_image = cv2.erode(binary_image, kernel, iterations=1)

# 打印去除噪点后的图像
plt.imshow(eroded_image, cmap='gray')
plt.title('Eroded Image')
plt.show()

# 应用膨胀操作
dilated_image = cv2.dilate(eroded_image, kernel, iterations=1)

# 打印突出图像特征后的图像
plt.imshow(dilated_image, cmap='gray')
plt.title('Dilated Image')
plt.show()

# 中值滤波去除小白点
median_filtered_image = cv2.medianBlur(dilated_image, 5)  # 修改滤波器大小为5

# 打印中值滤波后的图像
plt.imshow(median_filtered_image, cmap='gray')
plt.title('Median Filtered Image')
plt.show()

# 应用闭运算
closed_image = cv2.morphologyEx(median_filtered_image, cv2.MORPH_CLOSE, kernel)

# 打印填充闭合区域后的图像
plt.imshow(closed_image, cmap='gray')
plt.title('Closed Image')
plt.show()

# Canney边缘检测
edges = cv2.Canny(closed_image, 100, 200)

# 打印边缘检测结果
plt.imshow(edges, cmap='gray')
plt.title('Edges')
plt.show()

# 创建保存目录
if not os.path.exists('chars'):
    os.makedirs('chars')

# 保存图像到 chars 目录
plt.imsave('chars/grayscale_image.jpg', image, cmap='gray')
plt.imsave('chars/binary_image.jpg', binary_image, cmap='gray')
plt.imsave('chars/eroded_image.jpg', eroded_image, cmap='gray')
plt.imsave('chars/dilated_image.jpg', dilated_image, cmap='gray')
plt.imsave('chars/median_filtered_image.jpg', median_filtered_image, cmap='gray')
plt.imsave('chars/closed_image.jpg', closed_image, cmap='gray')
plt.imsave('chars/edges.jpg', edges, cmap='gray')
